﻿using Domain.User;
using Infratructure.Interface;
using Microsoft.EntityFrameworkCore;

namespace MES.Server.API.Helpers
{
    public static class DocumentCodeHelper
    {
        /// <summary>
        /// 生成编码（根据业务实体）
        /// </summary>
        public static async Task<string> GenerateCodeAsync(IRepository<DocumentCodeRule> ruleRepo, string businessEntity)
        {
            // 获取对应业务实体的编码规则
            var rule = await ruleRepo.GetAll()
                .FirstOrDefaultAsync(r => r.BusinessEntity == businessEntity);

            if (rule == null)
            {
                // 如果没有配置规则，使用默认规则
                return GenerateDefaultCode(businessEntity);
            }

            return await GenerateCodeByRuleAsync(ruleRepo, rule);
        }

        /// <summary>
        /// 根据规则生成编码
        /// </summary>
        private static async Task<string> GenerateCodeByRuleAsync(IRepository<DocumentCodeRule> ruleRepo, DocumentCodeRule rule)
        {
            var now = DateTime.Now;
            var datePart = GetDatePart(rule.RuleType, now);

            // 简化实现：查询当天已有记录数量 + 1
            var todayCount = await ruleRepo.GetAll()
                .CountAsync(r => r.BusinessEntity == rule.BusinessEntity &&
                               r.CreateTime.Date == now.Date);

            var numberPart = (todayCount + 1).ToString().PadLeft(rule.NumberDigits, '0');

            if (string.IsNullOrEmpty(rule.Connector))
            {
                return $"{rule.Prefix}{datePart}{numberPart}";
            }
            else
            {
                return $"{rule.Prefix}{rule.Connector}{datePart}{rule.Connector}{numberPart}";
            }
        }

        /// <summary>
        /// 预览编码规则
        /// </summary>
        public static string PreviewCode(DocumentCodeRule rule)
        {
            var now = DateTime.Now;
            var datePart = GetDatePart(rule.RuleType, now);
            var numberPart = "001".PadLeft(rule.NumberDigits, '0');

            if (string.IsNullOrEmpty(rule.Connector))
            {
                return $"{rule.Prefix}{datePart}{numberPart}";
            }
            else
            {
                return $"{rule.Prefix}{rule.Connector}{datePart}{rule.Connector}{numberPart}";
            }
        }

        private static string GetDatePart(string ruleType, DateTime date)
        {
            return ruleType switch
            {
                "年" => date.ToString("yyyy"),
                "年月" => date.ToString("yyyyMM"),
                "年月日" => date.ToString("yyyyMMdd"),
                "无" => string.Empty,
                _ => string.Empty
            };
        }

        private static string GenerateDefaultCode(string businessEntity)
        {
            var prefix = businessEntity switch
            {
                "QualityInspection" => "QI",
                "ProductionOrder" => "PO",
                "PurchaseOrder" => "PUR",
                _ => "DOC"
            };

            return $"{prefix}{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";
        }
    }
}
